package com.zw.yzk.kabu.adapter;

import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.model.ClassifyDetailsModel;
import com.zw.yzk.kabu.model.GoodsClassifyModel;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by zhanwei on 2017/3/11.
 */

public class GoodsClassifyAdapter extends RecyclerView.Adapter<GoodsClassifyAdapter.Holder> {

    private List<GoodsClassifyModel> dataList;

    public GoodsClassifyAdapter(List<GoodsClassifyModel> dataList) {
        this.dataList = new ArrayList<>();
        if (dataList != null) {
            this.dataList.addAll(dataList);
        }
    }

    public void refresh(List<GoodsClassifyModel> dataList) {
        this.dataList.clear();
        if (dataList != null) {
            this.dataList.addAll(dataList);
        }
        notifyDataSetChanged();
    }

    @Override
    public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_goods_classify, parent, false);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(final Holder holder, int position) {
        final GoodsClassifyModel model = dataList.get(position);
        holder.classify.setText(model.getClassify());
        holder.itemView.setBackgroundColor(Color.parseColor(model.isSelected() ? "#FFFFFF" : "#F5F5F5"));

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (model.isSelected()) {
                    return;
                }
                for (GoodsClassifyModel m : dataList) {
                    m.setSelected(false);
                }
                dataList.get(holder.getAdapterPosition()).setSelected(true);
                notifyDataSetChanged();
                if (listener != null) {
                    listener.onClassifyClicker(model.getId());
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    public static class Holder extends RecyclerView.ViewHolder {

        @Bind(R.id.classify)
        TextView classify;

        public Holder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private OnClassifyClickedListener listener;

    public interface OnClassifyClickedListener {
        void onClassifyClicker(int type);
    }

    public void setOnClassifyClickedListener(OnClassifyClickedListener listener) {
        this.listener = listener;
    }
}
